package com.link2room.blaster.facade.impl;

import com.link2room.blaster.constant.MsgConstant;
import com.link2room.blaster.dto.innerUse.MsgSendParamDto;
import com.link2room.blaster.common.FreemarkerUtil;
import com.link2room.blaster.facade.ISendTemplateMsgFacadeService;
import com.link2room.blaster.feign.ironhide.HotelBaseInfoFeignService;
import com.link2room.common.constant.BaseConstant;
import com.link2room.common.dto.result.base.BaseResultDto;
import com.link2room.common.dto.result.base.HotelBaseInfoDto;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.util.JacksonUtil;
import com.link2room.common.util.StringUtil;
import com.link2room.common.util.SysoptionUtil;
import com.link2room.blaster.entity.MsgTemplate;
import com.link2room.ironhide.dto.param.inside.HotelBaseInfoInsideParamDto;
import com.tencent.client.OfficialAccountClient;
import com.tencent.protocol.officialAccount.CustomSendProtocol;
import com.tencent.protocol.officialAccount.message.template.send.TemplateSendResDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by LN on 2016/11/9.
 */
@Component("sendWxTemplateMsgFacadeService")
public class SendTemplateMsgFacadeServiceImpl extends BaseFacadeImpl implements ISendTemplateMsgFacadeService {
    @Autowired
    private HotelBaseInfoFeignService hotelBaseInfoFeignService;

    private void send(MsgSendParamDto paramDto) throws Exception {
        String lhotelGroupCode = paramDto.getLhotelGroupCode();
        String templateCode = paramDto.getTemplateCode();
        String channel = paramDto.getChannel();
        if(StringUtil.isBlank(lhotelGroupCode) ||StringUtil.isBlank(templateCode) || StringUtil.isBlank(channel)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(), BaseSysExceptionEnum.INVALID_PARA.getMsg()+""
                    ,BaseConstant.SysExceptionConstant.BIZ_TYPE.BLASTER);
        }
        MsgTemplate template = findTemplate(paramDto.getLhotelGroupCode(), paramDto.getLhotelCode(), paramDto.getChannel(), paramDto.getTemplateCode());
        if(template == null){
            return;
        }
        if(MsgConstant.CHANNEL.WECHAT.equals(template.getChannel())){
//            sendWXMsg(template,paramDto.getData());
            Map map = (Map) paramDto.getData();
            sendWXMsg(lhotelGroupCode,paramDto.getLhotelCode(),template,map);
        }
    }

    @Override
    public void sendHandler(MsgSendParamDto msgSendParamDto) throws Exception {

        Map map = (Map) msgSendParamDto.getData();
        String openid = (String) map.get("openid");
        if(StringUtil.isBlank(openid)){
            return;
        }
//        if(MsgConstant.CHANNEL.WECHAT.equals(dto.getChannel())){
        //TODO 暂时不做渠道处理，默认微信模板消息
        //预定成功
        if(MsgConstant.TEMPLET_CODE.ORDER_SUCCESS.equals(msgSendParamDto.getTemplateCode())){
//            MsgSendParamDto<ReservationBaseDto> paramDto = JacksonUtil.jsonToBeanByJavaType(messages, MsgSendParamDto.class, ReservationBaseDto.class);
            msgSendParamDto.setChannel(MsgConstant.CHANNEL.WECHAT);
            send(msgSendParamDto);

            map = (Map) msgSendParamDto.getData();
            String hotelCode = (String) map.get("lhotelCode");
            String lhotelGroupCode = (String) map.get("lhotelGroupCode");
            coordinateSend(lhotelGroupCode,hotelCode,openid);
        }
        if(MsgConstant.TEMPLET_CODE.CANCEL.equals(msgSendParamDto.getTemplateCode())){
//            MsgSendParamDto<ReservationBaseDto> paramDto = JacksonUtil.jsonToBeanByJavaType(messages, MsgSendParamDto.class, ReservationBaseDto.class);
            msgSendParamDto.setChannel(MsgConstant.CHANNEL.WECHAT);
            send(msgSendParamDto);
        }
        if(MsgConstant.TEMPLET_CODE.PAY_SUCCESS.equals(msgSendParamDto.getTemplateCode())){
//            MsgSendParamDto<ReservationBaseDto> paramDto = JacksonUtil.jsonToBeanByJavaType(messages, MsgSendParamDto.class, ReservationBaseDto.class);
            msgSendParamDto.setChannel(MsgConstant.CHANNEL.WECHAT);
            send(msgSendParamDto);
        }
        if(MsgConstant.CHANNEL.WECHA_CUSTOM_SEND.equals(msgSendParamDto.getChannel())){
            sendConstomMsg(msgSendParamDto);
        }

    }


    private void coordinateSend(String hotelGroupCode,String hotelCode  ,String openid ) throws Exception {
        Double lat ,  lon;
        HotelBaseInfoInsideParamDto param = new HotelBaseInfoInsideParamDto();
        param.setLhotelCode(hotelCode);
        param.setLhotelGroupCode(hotelGroupCode);
        BaseResultDto<HotelBaseInfoDto> hotelBaseInfoDtoBaseResultDto = hotelBaseInfoFeignService.hotelBaseInfoByLhotelCode(param.paramToMap());
        HotelBaseInfoDto hotelDto=hotelBaseInfoDtoBaseResultDto.getResultInfo();
        if(hotelDto==null){
            return;
        }
        if(StringUtil.isBlank(hotelDto.getLatitude()) &&  StringUtil.isBlank(hotelDto.getLongitude())){
            return;
        }
        lat = Double.valueOf(hotelDto.getLatitude());
        lon =  Double.valueOf(hotelDto.getLongitude());
        CustomSendProtocol cs = new CustomSendProtocol();
        cs.setTouser(openid);
        cs.setMsgtype("news");
        CustomSendProtocol.News news = new CustomSendProtocol.News();
        CustomSendProtocol.Articles article = new CustomSendProtocol.Articles();

        String markURL = "size:large|color:0xFFCCFF|label:k|"+lat.toString()+","+lon.toString();
        article.setPicurl("http://apis.map.qq.com/ws/staticmap/v2/" +
                "?center="+lat+","+lon+
                "&zoom=10" +
                "&size=600*300" +
                "&maptype=roadmap" +
                "&markers="+ URLEncoder.encode(markURL, "UTF-8")+
                "&key=PYOBZ-5ZRKP-JN7DO-LTV26-3XQME-Y2BDP");

        String url = SysoptionUtil.getSysOption(hotelGroupCode, null, BaseConstant.SysOptionConstant.Item.MAP_URL);
        if(StringUtil.isBlank(url)){
            return;
        }
        url = url + "?lhotelGroupCode="+hotelGroupCode
                +"&latitude="+lat.toString()
                +"&longitude="+lon.toString()
                +"&name="+hotelDto.getName()
                +"&address="+hotelDto.getAddress();
        article.setUrl(url);
        article.setTitle("地图导航");
        article.setDescription("酒店地址:"+hotelDto.getAddress());
        List<CustomSendProtocol.Articles> articles = new ArrayList<CustomSendProtocol.Articles>();
        articles.add(article);
        news.setArticles(articles);
        cs.setNews(news);
        String token = this.getOfficialAccountsToken(hotelGroupCode, null);
        OfficialAccountClient.customSend(token, cs);
    }

    /**
     * 发送微信消息
     * @param template
     * @throws Exception
     */
    //TODO 建立一个公共入参
//    private void sendWXMsg(MsgTemplate template,ReservationBaseDto resvDto) throws Exception {
//        String str = FreemarkerUtil.getMsg(template,resvDto);
//        String openid = resvDto.getOpenid();
//        Map dateMap = (Map) JacksonUtil.jsonToBean(str, Map.class);
//        String token = this.getOfficialAccountsToken(template.getLhotelGroupCode(),template.getLhotelCode());
//        TemplateSendResDate res = OfficialAccountClient.sendTemplateMsg(token, dateMap, template.getTemplateId(), openid);
//        //记录
//        logWxTemplateMsg(resvDto.getLhotelGroupCode(),resvDto.getLhotelCode(),res,str);
//    }

    private void sendWXMsg(String lhotelGroupCode ,String hotelCode,MsgTemplate template,Map data) throws Exception {
        //TODO 转MAP取值未知
        String str = FreemarkerUtil.getMsg(template,data);
        String openid = (String) data.get("openid");
        Map dateMap = (Map) JacksonUtil.jsonToBean(str, Map.class);
        String token = this.getOfficialAccountsToken(template.getLhotelGroupCode(),template.getLhotelCode());
        TemplateSendResDate res = OfficialAccountClient.sendTemplateMsg(token, dateMap, template.getTemplateId(), openid);
        //记录
        logWxTemplateMsg(lhotelGroupCode,hotelCode,res,str);
//        logWxTemplateMsg(lhotelGroupCode,hotelCode,res,str);
    }
}
